package com.example.weather

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import com.example.weather.WeatherBean.DataBean.IndexBean
import com.google.gson.Gson
import org.xutils.common.Callback
import org.xutils.common.Callback.CommonCallback
import org.xutils.http.RequestParams
import org.xutils.x
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Objects

/**
 * @author Y7993
 * 城市天气 Fragment 类，用于显示选定城市的气象信息
 */
class CityWeatherFragment : BaseFragment(), View.OnClickListener {
    var tempTv: TextView? = null
    var cityTv: TextView? = null
    var conditionTv: TextView? = null
    var windTv: TextView? = null
    var tempRangeTv: TextView? = null
    var dateTv: TextView? = null
    var clothIndexTv: TextView? = null
    var carIndexTv: TextView? = null
    var coldIndexTv: TextView? = null
    var sportIndexTv: TextView? = null
    var raysIndexTv: TextView? = null
    var airIndexTv: TextView? = null
    var dayIv: ImageView? = null

    /**天气 */
    var futureLayout: LinearLayout? = null
    var outLayout: ScrollView? = null

    //以下为动态更新城市信息的
    var url1: String =
        "https://wis.qq.com/weather/common?source=pc&weather_type=observe|index|rise|alarm|air|tips|forecast_24h&province="
    var url2: String = "&city="
    var city: String? = null
    var provice: String? = null
    private var index: IndexBean? = null

    /**
     * 创建视图
     * @param inflater 用于加载视图的布局填充器
     * @param container 父容器
     * @param savedInstanceState 保存的实例状态
     * @return 创建的视图
     */
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.fragment_city_weather, container, false)
        initView(view)
        exchangeBg()
        val bundle = arguments
        var provice_city: String? = null
        if (bundle != null) {
            provice_city = bundle.getString("city")
        }
        println(provice_city)
        city = provice_city
        provice = GetProvice(city!!)
        val url = url1 + provice + url2 + city
        //          调用父类获取数据的方法
        val rp = RequestParams(url)
        x.http().get<String?>(rp, this.MyCallBackk())
        return view
    }

    /**
     * 自定义回调类，用于处理请求结果
     */
    inner class MyCallBackk : CommonCallback<String?> {
        override fun onSuccess(result: String?) {
            //        解析并展示数据
            try {
                parseShowData(result)
            } catch (e: ParseException) {
                e.printStackTrace()
            }
        }

        override fun onError(ex: Throwable?, isOnCallback: Boolean) {
            println("ERROR")
        }

        override fun onCancelled(cex: Callback.CancelledException?) {
        }

        override fun onFinished() {
            println("完成")
        }
    }

    /**
     * 初始化视图组件
     * @param view 要初始化的视图
     */
    private fun initView(view: View) {
        //初始化控件
        tempTv = view.findViewById<TextView>(R.id.frag_tv_currenttemp)
        cityTv = view.findViewById<TextView>(R.id.frag_tv_city)
        conditionTv = view.findViewById<TextView>(R.id.frag_tv_condition)
        windTv = view.findViewById<TextView>(R.id.frag_tv_wind)
        tempRangeTv = view.findViewById<TextView>(R.id.frag_tv_temprange)
        dateTv = view.findViewById<TextView>(R.id.frag_tv_date)
        clothIndexTv = view.findViewById<TextView>(R.id.frag_index_tv_dress)
        carIndexTv = view.findViewById<TextView>(R.id.frag_index_tv_washcar)
        coldIndexTv = view.findViewById<TextView>(R.id.frag_index_tv_cold)
        sportIndexTv = view.findViewById<TextView>(R.id.frag_index_tv_sport)
        raysIndexTv = view.findViewById<TextView>(R.id.frag_index_tv_rays)
        airIndexTv = view.findViewById<TextView>(R.id.frag_index_tv_air)
        futureLayout = view.findViewById<LinearLayout>(R.id.frag_center_layout)
        dayIv = view.findViewById<ImageView?>(R.id.frag_iv_today)
        outLayout = view.findViewById<ScrollView>(R.id.out_layout)
        //设置监听
        carIndexTv!!.setOnClickListener(this)
        carIndexTv!!.setOnClickListener(this)
        coldIndexTv!!.setOnClickListener(this)
        sportIndexTv!!.setOnClickListener(this)
        raysIndexTv!!.setOnClickListener(this)
        airIndexTv!!.setOnClickListener(this)
    }

    //        换壁纸的函数
    fun exchangeBg() {
        val pref = requireActivity().getSharedPreferences("bg_pref", Context.MODE_PRIVATE)
        val bgNum = pref.getInt("bg", 2)
        when (bgNum) {
            0 -> outLayout!!.setBackgroundResource(R.mipmap.bg)
            1 -> outLayout!!.setBackgroundResource(R.mipmap.bg2)
            2 -> outLayout!!.setBackgroundResource(R.mipmap.bg3)
        }
    }

    //点击事件处理
    override fun onClick(view: View) {
        val builder = AlertDialog.Builder(context)
        var msg: String?

        if (view.id == R.id.frag_index_tv_dress) {
            builder.setTitle("穿衣指数")
            val cloth = index!!.clothes
            msg = cloth.info + "\n" + cloth.detail
            builder.setMessage(msg)
        } else if (view.id == R.id.frag_index_tv_washcar) {
            builder.setTitle("洗车指数")
            val car = index!!.carwash
            msg = car.info + "\n" + car.detail
            builder.setMessage(msg)
        } else if (view.id == R.id.frag_index_tv_cold) {
            builder.setTitle("感冒指数")
            val cold = index!!.cold
            msg = cold.info + "\n" + cold.detail
            builder.setMessage(msg)
        } else if (view.id == R.id.frag_index_tv_sport) {
            builder.setTitle("运动指数")
            val sport = index!!.sports
            msg = sport.info + "\n" + sport.detail
            builder.setMessage(msg)
        } else if (view.id == R.id.frag_index_tv_rays) {
            builder.setTitle("紫外线指数")
            val ultraviolet = index!!.ultraviolet
            msg = ultraviolet.info + "\n" + ultraviolet.detail
            builder.setMessage(msg)
        } else if (view.id == R.id.frag_index_tv_air) {
            builder.setTitle("空调指数")
            val umbrella = index!!.umbrella
            msg = umbrella.info + "\n" + umbrella.detail
            builder.setMessage(msg)
        }

        builder.setPositiveButton("确定", null)
        builder.show()
    }


    override fun onError(ex: Throwable?, isOnCallback: Boolean) {
//        数据库当中查找上一次信息显示在Fragment当中
    }

    /**
     * 解析并显示数据
     * @param result API 返回的天气数据
     * @throws ParseException 解析过程中可能抛出的异常
     */
    @SuppressLint("SetTextI18n")
    @Throws(ParseException::class)
    private fun parseShowData(result: String?) {
//        使用gson解析数据
        val weatherBean = Gson().fromJson<WeatherBean>(result, WeatherBean::class.java)
        val resultsBean = weatherBean.data
        index = resultsBean.index
        //        设置TextView
        cityTv!!.text = city
        println(result)
        //        获取今日天气情况
        val todayDataBean = resultsBean.observe
        val time = changeTime(todayDataBean.update_time)
        dateTv!!.text = "发布时间  $time"
        windTv!!.text = "风向 " + "西南风" + todayDataBean.wind_power + "级"
        tempRangeTv!!.text = "气压  " + todayDataBean.pressure + "hPa"
        conditionTv!!.text = todayDataBean.weather_short
        //        获取实时天气温度情况，需要处理字符串
        tempTv!!.text = todayDataBean.degree + "°C"
        //        获取未来三天的天气情况，加载到layout当中
        val futureList = resultsBean.forecast_24h
        @SuppressLint("InflateParams") val itemView =
            LayoutInflater.from(activity).inflate(R.layout.item_main_center, null)
        itemView.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        futureLayout!!.addView(itemView)
        val idateTv = itemView.findViewById<TextView>(R.id.item_center_tv_date)
        val iconTv = itemView.findViewById<TextView>(R.id.item_center_tv_con)
        val itemprangeTv = itemView.findViewById<TextView>(R.id.item_center_tv_temp)
        val wind = itemView.findViewById<TextView>(R.id.item_center_tv_winddirection)
        //          获取对应的位置的天气情况
        idateTv.text = futureList.`get_$2`().time + "   明天"
        iconTv.text = futureList.`get_$2`().day_weather
        wind.text = futureList.`get_$2`().day_wind_direction
        itemprangeTv.text = futureList.`get_$2`().min_degree + "~" + futureList.`get_$2`()
            .max_degree + "°C"

        @SuppressLint("InflateParams") val itemView3 =
            LayoutInflater.from(activity).inflate(R.layout.item_main_center, null)
        itemView.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        futureLayout!!.addView(itemView3)
        val idateTv3 = itemView3.findViewById<TextView>(R.id.item_center_tv_date)
        val iconTv3 = itemView3.findViewById<TextView>(R.id.item_center_tv_con)
        val itemprangeTv3 = itemView3.findViewById<TextView>(R.id.item_center_tv_temp)
        val wind3 = itemView3.findViewById<TextView>(R.id.item_center_tv_winddirection)
        //          获取对应的位置的天气情况
        idateTv3.text = futureList.`get_$3`().time + "   后天"
        iconTv3.text = futureList.`get_$3`().day_weather
        wind3.text = futureList.`get_$3`().day_wind_direction
        itemprangeTv3.text = futureList.`get_$3`().min_degree + "~" + futureList.`get_$3`()
            .max_degree + "°C"

        @SuppressLint("InflateParams") val itemView2 =
            LayoutInflater.from(activity).inflate(R.layout.item_main_center, null)
        itemView.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        futureLayout!!.addView(itemView2)
        val idateTv2 = itemView2.findViewById<TextView>(R.id.item_center_tv_date)
        val iconTv2 = itemView2.findViewById<TextView>(R.id.item_center_tv_con)
        val itemprangeTv2 = itemView2.findViewById<TextView>(R.id.item_center_tv_temp)
        val wind2 = itemView2.findViewById<TextView>(R.id.item_center_tv_winddirection)
        //          获取对应的位置的天气情况
        idateTv2.text = futureList.`get_$4`().time + " 大后天"
        iconTv2.text = futureList.`get_$4`().day_weather
        wind2.text = futureList.`get_$4`().day_wind_direction
        itemprangeTv2.text = futureList.`get_$4`().min_degree + "~" + futureList.`get_$4`()
            .max_degree + "°C"
    }

    /**
     * 时间格式化
     * @param update_time 原始时间字符串
     * @return 格式化后的时间字符串
     * @throws ParseException 解析过程中可能抛出的异常
     */
    @Throws(ParseException::class)
    private fun changeTime(update_time: String): String {
        @SuppressLint("SimpleDateFormat") val sf1 = SimpleDateFormat("yyyyMMddHHmm")
        @SuppressLint("SimpleDateFormat") val sf2 = SimpleDateFormat("yyyy-MM-dd HH:mm")
        var sfstr: String = sf2.format(Objects.requireNonNull<Date?>(sf1.parse(update_time)))
        return sfstr
    }

    /**
     * 根据城市名称获取省份信息
     * @param city 城市名称
     * @return 省份名称
     */
    private fun GetProvice(city: String): String {
        val Citys = arrayOf<String?>(
            "北京",
            "上海",
            "广东省 广州",
            "广东省 深圳",
            "广东省 珠海",
            "广东省 佛山",
            "江苏省 南京",
            "江苏省 苏州",
            "福建省 厦门",
            "湖南省 长沙",
            "四川省 成都",
            "福建省 福州",
            "浙江省 杭州",
            "湖北省 武汉",
            "山东省 烟台",
            "陕西省 西安",
            "山西省 太原",
            "辽宁省 沈阳",
            "重庆",
            "天津",
            "广西省 南宁"
        )
        for (s in Citys) {
            if (s!!.contains(city)) {
                provice = s.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
                break
            }
        }
        return provice!!
    }
}
